/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedbean.ProductManagement;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;
import merlion.common.util.Consts.ProductType;
import merlion.crm.slcm.session.SLCSessionBeanLocal;
import merlion.mrp.pmm.entity.FinishedGood;
import merlion.mrp.pmm.session.ProductManagementSessionLocal;
import merlion.mrp.ppm.entity.Product;
import merlion.scm.icm.entity.ProductInventoryRecord;
import org.primefaces.context.RequestContext;

/**
 *
 * @author Zhu Xin, Zhang Ying, Kenneth
 */
@ManagedBean(name = "pmManagerBean")
@ViewScoped
public class ProductManagementManagerBean {

    private Collection<FinishedGood> fds;
    @EJB
    private ProductManagementSessionLocal pmSessionBean;
    @EJB
    private SLCSessionBeanLocal slcSessionBean;
    private List<Product> products;
    private FinishedGood fg;
    private Long fgTypeId;

    /** Creates a new instance of ProductManagementManagerBean */
    public ProductManagementManagerBean() {
        fds = new ArrayList<FinishedGood>();
        products = new ArrayList<Product>();
        fg = new FinishedGood();
    }

    public Long getFgTypeId() {
        return fgTypeId;
    }

    public void setFgTypeId(Long fgTypeId) {
        this.fgTypeId = fgTypeId;
    }

    public Collection<FinishedGood> getFds() {
        return fds;
    }

    public void setFds(Collection<FinishedGood> fds) {
        this.fds = fds;
    }

    public ProductManagementSessionLocal getPmSessionBean() {
        return pmSessionBean;
    }

    public void setPmSessionBean(ProductManagementSessionLocal pmSessionBean) {
        this.pmSessionBean = pmSessionBean;
    }

    public List<Product> getAllProduct() {

        setProducts(slcSessionBean.getAllProduct());

        return products;
    }

    public List<Product> getProducts() {
        return products;
    }

    public void setProducts(List<Product> products) {
        this.products = products;
    }

    public FinishedGood getFg() {
        return fg;
    }

    public void setFg(FinishedGood fg) {
        this.fg = fg;
    }

    public SLCSessionBeanLocal getSlcSessionBean() {
        return slcSessionBean;
    }

    public void setSlcSessionBean(SLCSessionBeanLocal slcSessionBean) {
        this.slcSessionBean = slcSessionBean;
    }

    public Collection<FinishedGood> viewAllFinishedGoods() {
        setFds(pmSessionBean.getAllFinishedGoods());
        return fds;
    }

    public SelectItem[] createFilterOptions() {
        products = slcSessionBean.getAllProduct();
        SelectItem[] options = new SelectItem[products.size() + 1];

        options[0] = new SelectItem("", "Select");
        for (int i = 0; i < products.size(); i++) {
            options[i + 1] = new SelectItem(products.get(i).getProductType(), products.get(i).getProductType());
        }

        return options;
    }

    public String createNewFD() {
        fg = new FinishedGood();
        return null;
    }

    public String createFinishedGoodsRecord() {

        RequestContext context = RequestContext.getCurrentInstance();

        boolean valid = true;

        //Product Type required
        if (fgTypeId == (long) -1) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Product Type", "cannot be empty."));
            valid = false;
            context.addCallbackParam("valid", valid);
            return null;
        }

        //Quantity: required, not <=0
        if (fg.getQuantity() == null) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Quantity", "cannot be empty."));
            valid = false;
            context.addCallbackParam("valid", valid);
            return null;
        } else {
            if (fg.getQuantity() <= 0) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Quantity", "cannot be <= 0."));
                valid = false;
                context.addCallbackParam("valid", valid);
                return null;
            }
        }

        // Get Product
        Product product = slcSessionBean.getProductById(fgTypeId);
        fg.replaceBatchNoWithAlpha(product.getProductType());
//        fg.setBasePrice(product.getBasePrice());
        //fg.setInventory(null);

        //check duplicates
        if (pmSessionBean.exist(fg.getBatchNo())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "This batch already exists,", "please choose to update"));
            valid = false;
            context.addCallbackParam("valid", valid);
            return null;
        }
        
        // check whether the produced # is within +-10%
        /*
        if (!pmSessionBean.checkPercDifferenceFromPlannedDaily(fg, product.getProductType())){
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessful", "The inputted quanty differs too much from the planned quantity."));
            valid = false;
            context.addCallbackParam("valid", valid);
            return null;
        }*/

        if (valid) {
            if(pmSessionBean.createFinishedGoodsRecord(fg, product) != null)
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Finished Goods Record", "successfully created."));
            else
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Finished Goods Record", "failed to create. Insufficient raw materials."));
        }
        context.addCallbackParam("valid", valid);
        return null;
    }

    public boolean renderUpdate(Long id) {
        boolean render = false;
        if (fds.isEmpty()) {
            return false;
        }

        pmSessionBean.getFinishedGoodsById(id);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String mDate = sdf.format(fg.getDateManufactured());
        String today = sdf.format(new Timestamp(new Date().getTime()));
        if (mDate.equals(today)) {
            render = true;
        }

        return render;
    }

    public String updateFinishedGoods(Long id) {
        fg = pmSessionBean.getFinishedGoodsById(id);
        return null;
    }

    public String updateFinishedGoodsRecord() {

        RequestContext context = RequestContext.getCurrentInstance();

        boolean valid = true;

        //Quantity: required, not <=0
        if (fg.getQuantity() == null) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Quantity", "cannot be empty."));
            valid = false;
            context.addCallbackParam("valid", valid);
            return null;
        } else {
            if (fg.getQuantity() <= 0) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Quantity", "cannot be <= 0."));
                valid = false;
                context.addCallbackParam("valid", valid);
                return null;
            }
        }

        if (valid) {
            // Get Produc
            pmSessionBean.updateFinishedGoodsRecord(fg);
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Finished Goods Record", "successfully updated."));
        }
        context.addCallbackParam("valid", valid);
        return null;
    }
}
